import {getToken, removeToken, setToken} from "@utils/auth";

import local from "@/utils/store/localStorage";
import {getUserInfo, login, logout} from "@api/User";

const INFO_KEY = "userInfo";

const user = {
    state: {
        token: getToken(),
        id: 0,
        info: local.getUserInfo() || {}
    },
    mutations: {
        SET_TOKEN(state, token) {
            state.token = token;
        },
        SET_ID(state, id) {
            state.id = id;
        },
        SET_INFO(state, info) {
            state.info = info;
            state.id = info.id;
            local.set(INFO_KEY, info);
        }
    },
    actions: {
        Login({commit, state}, loginData) {
            const username = loginData.username.trim();
            const password = loginData.password;
            const captcha = loginData.captcha;
            return new Promise((resolve, reject) => {
                login(username, password, captcha)
                    .then(res => {
                        setToken(res.data.token);
                        commit("SET_TOKEN", res.data.token);
                        commit("SET_INFO", res.data);
                        commit("SET_ID", res.data.id);
                        resolve(res);
                    })
                    .catch(error => {
                        reject(error);
                    });
            });
        },
        Logout({commit, state}) {
            return new Promise((resolve, reject) => {
                logout()
                    .then(v => {
                        commit("SET_TOKEN", "");
                        commit("SET_INFO", {});
                        commit("SET_ID", 0);
                        removeToken();
                        resolve();
                    })
                    .catch(e => {
                        reject(e);
                    });
            });
        },
        UpdateUserInfo({commit, state}) {
            return new Promise((resolve, reject) => {
                getUserInfo().then(v => {
                    commit("SET_INFO", v.data);
                    commit("SET_ID", v.data.id);
                    resolve(v.data);
                }).catch(e => {
                    reject(e);
                })
            });
        },
        saveUserInfo({commit, state}, userInfo){
            return new Promise((resolve, reject) =>{
                commit("SET_INFO", userInfo);
                commit("SET_ID", userInfo.id)
                resolve(userInfo);
            })
        },
        FedLogOut({commit}) {
            return new Promise(resolve => {
                commit("SET_TOKEN", "");
                commit("SET_INFO", {});
                commit("SET_ID", 0);
                removeToken();
                resolve();
            });
        }
    }
};

export default user;
